package com.example.nettydemo.handle;

import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * NettyClient MessageHandler
 *
 * @author liushuai
 * @date 2020-08-25 16:52
 */
@Slf4j
// public class NettyClientMessageHandler extends ChannelInboundHandlerAdapter {
public class NettyStringMessageHandler extends SimpleChannelInboundHandler<String> {
    private StringBuffer stringBuffer = new StringBuffer();

    @Override
    public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        log.debug("msg {}: {}", ctx.channel().id(), msg);
        stringBuffer.append(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
        String body = stringBuffer.toString();
        stringBuffer.delete(0, stringBuffer.length());

        // if (StringUtils.countMatches(body, "JSONSENDOVER") != 1 || !body.endsWith("JSONSENDOVER")) {
        //     log.error("channelReadComplete: {}", body);
        //     return;
        // }
        if ("".equals(body)) {
            return;
        }
        try {
            // String jsonStr = body.replace("JSONSENDOVER", "");
            JSONObject jsonObject = JSONObject.parseObject(body);
            String type = jsonObject.getString("type");
            Channel channel = ctx.channel();

            switch (type) {
                case "heartbeat":
                    log.debug("{} 心跳返回: {}", channel.id(), body);
                    break;
                case "service":
                    log.debug("接收数据 channel.id(): {}", channel.id());
                    log.debug("接收数据 jsonObject: {}", jsonObject.toJSONString());
                    NettyClientPool.poolMap.get(channel.remoteAddress()).release(channel);
                    //     // new Thread(new ProcessResultRunner(msg.getImage(), msg.getData(), msg.getFileName(),
                    break;
                default:
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}